package service

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// 中间件校验数据
func Middleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println(">> 中间件执行开始 <<")
		token := c.Query("token")
		if token != "123456" {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
				"code": http.StatusBadRequest,
				"msg":  "token错误",
				"data": nil,
			})
			return
		}

		ageStr := c.Query("age")
		age, err := strconv.Atoi(ageStr) //string转int
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, "输入的年龄错误，必须是整数")
			return
		}
		if age < 0 || age > 120 {
			c.AbortWithStatusJSON(http.StatusBadRequest, "输入的年龄错误，必须在0-120范围内")
			return
		}

		fmt.Println(">> 中间件执行结束 <<")
		c.Next() //执行后续操作
	}
}

// 登录中间件
func AuthMiddleware() gin.HandlerFunc {
	//初始化用户
	accounts := gin.Accounts{ // gin.Accounts 是 map[string]string 类型
		"admin":    "123456",
		"zhangsan": "888888",
	}
	//动态添加用户
	accounts["lisi"] = "666666"
	accounts["wangwu"] = "777777"
	//将用户添加到登录中间件中
	auth := gin.BasicAuth(accounts)
	return auth
}
